import { reactive, ref } from 'vue'

/**
 * 表单状态管理钩子
 * @param {Object} initialValues - 表单初始值
 * @param {Object} rules - 表单验证规则
 * @returns {Object}
 */
export function useForm(initialValues = {}, rules = {}) {
  const formData = reactive({ ...initialValues })
  const formRef = ref(null)
  
  /**
   * 重置表单
   */
  const resetForm = () => {
    Object.keys(formData).forEach(key => {
      if (initialValues.hasOwnProperty(key)) {
        formData[key] = initialValues[key]
      } else {
        delete formData[key]
      }
    })
    
    if (formRef.value) {
      formRef.value.resetFields()
    }
  }
  
  /**
   * 校验表单
   * @returns {Promise}
   */
  const validateForm = () => {
    return new Promise((resolve, reject) => {
      if (!formRef.value) {
        resolve(formData)
        return
      }
      
      formRef.value.validate(valid => {
        if (valid) {
          resolve(formData)
        } else {
          reject(new Error('表单验证失败'))
        }
      })
    })
  }
  
  /**
   * 提交表单
   * @param {Function} submitFn - 提交函数
   * @returns {Promise}
   */
  const submitForm = async (submitFn) => {
    try {
      const values = await validateForm()
      return await submitFn(values)
    } catch (error) {
      console.error('表单提交失败', error)
      return Promise.reject(error)
    }
  }
  
  return {
    formData,
    formRef,
    resetForm,
    validateForm,
    submitForm
  }
} 